package com.example.account.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.example.account.service.AccountService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;


@RestController
public class AccountController {

	private static final String SUCCESS = "SUCCESS";
	private static final String FAIL = "FAIL";

	private final AccountService accountService;
	private final Random random;

	public AccountController(AccountService accountService) {
		this.accountService = accountService;
		this.random = new Random();
	}

	@PostMapping(value = "/account", produces = "application/json")
	@SentinelResource(value = "/seata/feign", fallback = "accountFallback")
	public String account(String userId, int money) {
		// 随机模拟熔断
		if (random.nextBoolean()) {
			throw new RuntimeException("this is a mock Exception");
		}
		int result = accountService.debit(userId, money);
		if (result == 1) {
			return SUCCESS;
		}
		return FAIL;
	}

	// 熔断降级
	public String accountFallback() {
		return "熔断降级";
	}
}
